package cn.worldyao.homework.controller;

import cn.worldyao.homework.Tools;
import cn.worldyao.homework.entity.KeClass;
import cn.worldyao.homework.entity.StuClassR;
import cn.worldyao.homework.entity.Teachers;
import cn.worldyao.homework.entity.WorkKe;
import cn.worldyao.homework.service.KeClassService;
import cn.worldyao.homework.service.StuClassRService;
import cn.worldyao.homework.service.TeachersService;
import cn.worldyao.homework.service.WorkKeService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yaozi
 * @since 2020-05-07
 */
@Controller
@RequestMapping("/teachers")
@Slf4j
public class TeachersController {

    @Autowired
    TeachersService teachersService;
    @Autowired
    KeClassService keClassService;
    @Autowired
    WorkKeService workKeService;
    @Autowired
    StuClassRService stuClassRService;


    @PostMapping("teareg")
    public ModelAndView tregister(@RequestBody(required = false) Teachers teachers) {
        log.info("\n-----tregister-----\n");
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("flag", false);
        if (!teachersService.checkTLoginNameExist(teachers.getLoginName())) {
            teachers.setSalt(Tools.getSalt8());
            teachers.setPassword(Tools.MD5Pwd(teachers.getPassword(), teachers.getSalt()));
            teachers.setUpdateTime(LocalDateTime.now());
            if (teachersService.save(teachers)) {

//                    modelAndView.addObject("str2",str2);
                //这里的url是服务器内地址，不能是任意地址；
//                return "foward:/tlogin.html";
                modelAndView.addObject("flag", true);
//                return "redirect:/tlogin.html";
            }
        }
        return modelAndView;
    }


    @PostMapping("tvalogName")
    @ResponseBody
    public ModelAndView tValidateLoginName(@RequestParam String loginName) {
        log.info("\n-----tregister-----\n");
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        if (teachersService.checkTLoginNameExist(loginName)) {
            modelAndView.addObject("msg", "用户名已存在");
            modelAndView.addObject("flag", false);
        } else {
            modelAndView.addObject("flag", true);
        }
        return modelAndView;
    }

    @PostMapping("tlogin")
    public String tLogin(@RequestParam("userName") String username, @RequestParam("passWord") String password, HttpSession session) {
        log.info("\n-----tLogin-----\n");
        Teachers teachers = new Teachers();
        teachers.setPassword(password);
        teachers.setLoginName(username);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("flag", false);
        Teachers teachers1 = teachersService.tLogin(teachers);
        if (teachers1 != null) {
            session.setAttribute("user", teachers1);
            modelAndView.addObject("flag", true);
            log.info("\n-----{}tLogin OK-----\n", teachers1);
            return "redirect:/tindex.html";
        } else {
            return null;
        }
    }

    @PostMapping("taddclass")
    public ModelAndView tAddClass(@RequestParam String className, HttpSession session) {
        log.info(className);
        log.info("\n-----tAddClass-----\n");
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        if (!"".equals(className) && !"".equals(className.trim())) {
            Object object = session.getAttribute("user");
            if (object instanceof Teachers) {
                KeClass keClass = new KeClass();
                keClass.setClassName(className);
                keClass.setClassTcId(((Teachers) object).getId());
                boolean flag = keClassService.save(keClass);
                modelAndView.addObject("flag", flag);
                modelAndView.addObject("msg", "{}添加课程成功！");
            } else {
                modelAndView.addObject("msg", "非法操作！");
            }
        }
        return modelAndView;
    }

    @GetMapping("tclasslist")
    @ResponseBody
    public String tClassList() throws JsonProcessingException {
        log.info("\n-----tclasslist-----\n");
//        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        ObjectMapper mapper = new ObjectMapper();

//        Foo foo = mapper.readValue(json, Foo.class);
//        Object object = session.getAttribute("user");
//        if (object instanceof Teachers) {
        List<KeClass> flag = keClassService.getClassList(null);
        String json = mapper.writeValueAsString(flag);
//            modelAndView.addObject("flag", flag);
//            modelAndView.addObject("msg", "{}添加课程成功！");
//        } else {
//            modelAndView.addObject("data", "非法操作！");
//        }
        log.info(json);


        return json;
    }

    @GetMapping("tmyclasses")
    @ResponseBody
    public String tMyClasses(HttpSession session) throws JsonProcessingException {
        log.info("\n-----tclasslist-----\n");
        ObjectMapper mapper = new ObjectMapper();
        Object object = session.getAttribute("user");
//        if (object instanceof Teachers) {
        List<KeClass> flag = keClassService.getMyClasses(null);
        String json = mapper.writeValueAsString(flag);
//        } else {
//            modelAndView.addObject("data", "非法操作！");
//        }
        log.info(json);

        return json;
    }


    @PostMapping("tkeworkkist")
    @ResponseBody
    public String tKeWorkList(HttpSession session) throws JsonProcessingException {
        log.info("\n-----tkeworkkist-----\n");


        ObjectMapper mapper = new ObjectMapper();
//        Object object = session.getAttribute("user");
//        if (object instanceof Teachers) {
        List<WorkKe> flag = workKeService.getKeWorkList();
        String json = mapper.writeValueAsString(flag);
//        } else {
//            modelAndView.addObject("data", "非法操作！");
//        }
        log.info(json);

        return json;
    }

    /**
     * 添加作业
     *
     * @param classId
     * @param workName
     * @param subTime
     * @param workDesc
     * @param session
     * @throws JsonProcessingException
     * @throws ParseException
     */
    @PostMapping("taddwork")
    @ResponseBody
    public boolean tAddWork(@RequestParam Integer classId, @RequestParam String workName,
                            @RequestParam String subTime, @RequestParam String workDesc,
                            HttpSession session) throws JsonProcessingException, ParseException {
        log.info("\n-----taddwork-----\n");

        String[] subTimes = subTime.split("-");


        WorkKe ke = new WorkKe();

        ke.setKeId(classId);
        ke.setSubStart(Tools.DateTrans(subTimes[0]));
        ke.setSubEnd(Tools.DateTrans(subTimes[1]));
        ke.setWorkName(workName);
        ke.setWorkDesc(workDesc);

        boolean flag = workKeService.save(ke);
        return flag;


//        ObjectMapper mapper = new ObjectMapper();
//        Object object = session.getAttribute("user");
//        if (object instanceof Teachers) {
//        List<KeClass> flag = keClassService.getMyClasses(null);
//        String json = mapper.writeValueAsString(flag);
//        } else {
//            modelAndView.addObject("data", "非法操作！");
//        }
//        log.info(json);

//        return json;
    }


    @PostMapping("tlookclassapply")
    @ResponseBody
    public String tLookClassApply(
            HttpSession session) throws JsonProcessingException, ParseException {
        log.info("\n-----tLookClassApply-----\n");

        ObjectMapper mapper = new ObjectMapper();

        if (Tools.userIsTeacher(session)) {
            Teachers teachers = (Teachers) session.getAttribute("user");
            List<StuClassR> list = stuClassRService.getStudentAndClassByClassTeacher(teachers.getId());
            String json = mapper.writeValueAsString(list);
            log.info(json);
            return json;
        }
        return null;

    }

}
